package com.ming.ultlight

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.Toast
import com.ming.ultlight.ble.BluetoothLeService
import com.ming.ultlight.databinding.ActivityMainBinding

private const val TAG = "ult_MainActivity"
class MainActivity : AppCompatActivity() {
    private fun PackageManager.missingSystemFeature(name: String): Boolean = !hasSystemFeature(name)
    private lateinit var binding: ActivityMainBinding

    private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothManager.adapter
    }
    private val BluetoothAdapter.isDisabled: Boolean
        get() = !isEnabled

    // 蓝牙相关Service
    private lateinit var bluetoothService: BluetoothLeService

    private val REQUEST_ENABLE_BT :Int = 1

    // 用于绑定Service 连接设备
    // Code to manage Service lifecycle.
    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            componentName: ComponentName,
            service: IBinder
        ) {
            bluetoothService = (service as BluetoothLeService.LocalBinder).getService()
            initListView()
            Log.d(TAG, "main bind service success!!")
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            Log.d(TAG, "main unbind service success!!")
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //检测权限
        authCheck()
        //绑定service
        val gattServiceIntent = Intent(this, BluetoothLeService::class.java)
        bindService(gattServiceIntent, serviceConnection, BIND_AUTO_CREATE)
    }

    //初始化蓝牙设备发现列表
    fun initListView(){
        var deviceListView =findViewById<ListView>(R.id.list_devices_bond_le)
        deviceListView.adapter = bluetoothService.ledeviceAdapter
        deviceListView.setOnItemClickListener {
                adapterView, view, position, id ->
            bluetoothService.scanLeDevice(false) //停止扫描
//            val device = adapterView.adapter.getItem(position) as BluetoothDevice
            if(!bluetoothService.connect(position)){
                return@setOnItemClickListener
            }
            //跳转
//            var intent = Intent(LeMainActivity@this, LightControlActivity::class.java)
//            intent.putExtra("deviceAddress", device.address)
            startActivity(intent)
        }
    }

    // 蓝牙相关权限检测
    fun authCheck(){
        packageManager.takeIf { it.missingSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) }?.also {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show()
            finish()
        }
        bluetoothAdapter?.takeIf { it.isDisabled }?.apply {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE).apply {
                startActivityForResult(this, REQUEST_ENABLE_BT)
            }
        }
    }

    // 扫描蓝牙设备
    fun scanLe(view: View){
        bluetoothService.scanLeDevice(true)
    }
}